#!/bin/sh

. ~/.env

# Step 1: Check if there is a ping to the local address of the tunnel
ping -c 1 $VPN_IP > /dev/null 2>&1
if [ $? -ne 0 ]; then
    # Step 2: Check if wg0 network exists
    if ! ip link show wg0 > /dev/null 2>&1; then
        # Step 2.2: Create wg0 network
        ip link add dev wg0 type wireguard
    fi

    # Step 3: Check if the IP address is assigned to wg0
    if ! ip addr show wg0 | grep -q "$CAMERA_IP/24"; then
        # Step 3.2: Assign IP address to wg0
        ip address add dev wg0 $CAMERA_IP/24
    fi

    # Step 4: Load WireGuard configuration
    wg setconf wg0 /etc/wireguard.conf

    # Step 5: Raise the network
    ip link set up dev wg0
fi
